package models

import (
	"bytes"
	"encoding/json"
	"github.com/astaxie/beego/validation"
	//goerrors "github.com/go-errors/errors"
	"3rd/errors"
	"strconv"
)

const (
	ZH_CN = "zh-CN"
	EN_US = "en-US"
)

const (
	SUCCESS = iota
	InternalError
	ParseError
	ValidateError
	UnknownError

	MediaExists
	UserNameExists
	UnknownMedia
	RetryLater
	InvalidCaptcha
	InvalidPwd
	InvalidSession
	InvalidUser
)

var ErrMap map[string]map[int]string = map[string]map[int]string{
	"zh-CN": map[int]string{
		InternalError:  "服务器内部错误",
		ParseError:     "参数解析失败",
		ValidateError:  "参数验证失败",
		UnknownError:   "未知错误",
		MediaExists:    "号码已经被注册",
		UserNameExists: "用户名被注册过",
		UnknownMedia:   "号码类型不正确",
		RetryLater:     "请稍后再试",
		InvalidCaptcha: "验证码无效",
		InvalidPwd:     "用户名或密码错误",
		InvalidSession: "无效的会话",
		InvalidUser: "无效的用户",
	},
}

func ParseBody(body []byte, obj interface{}) error {
	return json.Unmarshal(body, obj)
}

func Validate(obj interface{}) error {
	valid := validation.Validation{}
	b, err := valid.Valid(obj)
	if err != nil {
		return err
	}
	if !b {
		var buffer bytes.Buffer
		for _, err := range valid.Errors {
			buffer.WriteString(err.Field + " " + err.String() + ";")
			if code, ex := strconv.Atoi(err.Key); ex == nil {
				return errors.New(code, buffer.String())
			}
		}
		return errors.New(ParseError, buffer.String())
	}
	return nil
}

func ParseBodyAndValidate(body []byte, obj interface{}) error {
	if err := json.Unmarshal(body, obj); err != nil {
		return err
	}
	return Validate(obj)
}
